package msjcalendar;

import java.util.ArrayList;
import java.util.GregorianCalendar;

import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import utility.XmlHelper;


/**
 * @author Markus
 *
 */
public class Calendar {
	
	/**.
	 *  Kalender mit Terminen
	 */
	private ArrayList<Event> eventList;
	
	
	/**
	 * 
	 */
	public Calendar() {
		this.eventList = new ArrayList<Event>();
	}
	
	/**
	 * @param xmlElement XML-Element the Calender will be constructed from
	 */
	public Calendar(final Element xmlElement) {
		this.eventList = new ArrayList<Event>();
		NodeList nodeList = xmlElement.getElementsByTagName("*");
		for (int i = 0; i < nodeList.getLength(); i++) {
			   Node node = nodeList.item(i);
			   if (node.getNodeType() == Node.ELEMENT_NODE) {
				   Element e = (Element) node;
				   if (e.getTagName() == "SingleEvent") {
					   this.eventList.add(new SingleEvent(e));
				   }
				   if (e.getTagName() == "RepeatingEvent") {
					   this.eventList.add(new RepeatingEvent(e));
				   }
			   }
		}
	}
	
	/**
	 * @param newEvent neuer Termin
	 */
	public void createEvent(final Event newEvent) {
		this.eventList.add(newEvent);
	}
	
	/**
	 * @param event bestehender Termin
	 */
	public void deleteEvent(final Event event) {
		ArrayList<Event> result = new ArrayList<Event>();
		for (Event e: this.eventList) {
			if (e.equals(event)) {
				result.add(e);
			}
		}
		if (result.size() > 0) {
			for (Event e: result) {
				this.eventList.remove(e);
			}
		}
	}
	
	/**
	 * @param date Datum eines Termins
	 * @return Liste der Termine
	 */
	public ArrayList<Event> getEvent(final GregorianCalendar date) {
		ArrayList<Event> result = new ArrayList<Event>();
		for (Event e: this.eventList) {
			if (e.isMatching(date)) {
				result.add(e);
			}
		}
		return result;
	}
	
	/**
	 * @return returns the xml-representation of the calendar
	 */
	public Element toXml() {
		Element result = XmlHelper.getXmlDoc().createElement("calendar");	
		for (Event e: this.eventList) {
			result.appendChild(e.toXml());
		}
		return result;
	}
	
	/**
	 * @param subject Betreff nach dem gesucht werden soll
	 * @return gibt Liste mit den gefundenen Terminen zurueck
	 */
	public ArrayList<Event> getEvent(final String subject) {
		ArrayList<Event> result = new ArrayList<Event>();
		for (Event e: this.eventList) {
			if (e.getSubject().equalsIgnoreCase(subject)) {
				result.add(e);
			}
		}
		return result;
	}
}